'''
Created on 06/04/2009

@author: Edward
'''
from im.event.eventmanager import EventManager
from im.timerservice.timerservicequeue import TimerServiceQueue
import datetime
import threading

class TimerServiceListener(threading.Thread):
    '''
    classdocs
    '''

    __timer_queue = None
    __event_manager = None
    STOP_EVENT = "STOP"
    
    def __init__(self, timer_queue):
        '''
        Constructor
        '''
        self.__timer_queue = timer_queue
        self.__event_manager = EventManager()
        threading.Thread.__init__(self)
            
    def run(self):
        while True:
            (timestamp, event) = self.__timer_queue.get()
            if event != self.STOP_EVENT:
                date_time_now = datetime.datetime.now()
                time_delta = timestamp - date_time_now
                zero_microseconds = datetime.timedelta(microseconds=0)            
                if time_delta <= zero_microseconds:
                    self.__event_manager.add_event(event)
                else:
                    self.__timer_queue.put(timestamp, event)
            else:
                break
            
    def stop_listener(self):
        timestamp = datetime.datetime.now()
        self.__timer_queue.put(timestamp, self.STOP_EVENT)    
        
if __name__ == "__main__":
    queue = TimerServiceQueue()
    ten_seconds = datetime.timedelta(seconds=10)
    now = datetime.datetime.now()
    future = now + ten_seconds
    print ten_seconds
    print now
    print future
    queue.put(future, "HELLO")
    while True:
        (timestamp, str) = queue.get()
        date_time_now = datetime.datetime.now()
        time_delta = timestamp - date_time_now
        zero_microseconds = datetime.timedelta(microseconds=0)  
        print date_time_now
        print time_delta
        print zero_microseconds
        if time_delta <= zero_microseconds:
            print str
            break;
        else:
            print "not yet"
            queue.put(future, "HELLO")
 